package net.example.model.contract;

import com.oraycn.omcs.utils.BufferUtils;
import com.oraycn.omcs.utils.SerializeUtils;

import net.example.utils.SerializeHelper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;

public class ChangeHeadImageContract {
    public ChangeHeadImageContract() { }
    public ChangeHeadImageContract(String userID, int headImageIndex, byte[] headImage)
    {
        this.UserID = userID;
        this.HeadImageIndex = headImageIndex;
        this.HeadImage = headImage;
    }
    public String UserID ;
    public int HeadImageIndex ;
    public byte[] HeadImage ;

    /// <summary>
    /// 当服务端向好友发送通知前，设置该字段为最新的版本号。
    /// </summary>
    public int UserLatestVersion ;

    public byte[] serialize() throws Exception {
        boolean headImageDataisNull = HeadImage==null||HeadImage.length==0;
        byte[] bUserID = UserID.getBytes(StandardCharsets.UTF_8);
        int contractLen = headImageDataisNull? 4 + 4 + 4 + 4 +bUserID.length+4: 4 + 4 + HeadImage.length + 4 + 4 +bUserID.length+4;
        ByteBuf body = BufferUtils.newBuffer();
        body.writeInt(contractLen);
        if(headImageDataisNull)
        {
            body.writeInt(-1);
        }
        else
        {
            body.writeInt(HeadImage.length);
            body.writeBytes(HeadImage);
        }
        body.writeInt(HeadImageIndex);
        body.writeInt(bUserID.length);
        body.writeBytes(bUserID);
        body.writeInt(UserLatestVersion);
        byte[] result = new byte[body.readableBytes()];
        System.arraycopy(body.array(),0,result,0,result.length);
        return result;
    }

    public void deserialize(byte[] info) throws IOException {
        ByteBuf buffer = SerializeHelper.wrappedBuffer(info);
        buffer.readInt();
        int headImgLength = buffer.readInt();
        if(headImgLength>0)
        {
            HeadImage = new byte[headImgLength];
            buffer.readBytes(HeadImage);
        }
        HeadImageIndex=buffer.readInt();
        UserID=SerializeUtils.readStrIntLen(buffer);
        UserLatestVersion=buffer.readInt();
    }
}
